﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class GameMain : MonoBehaviour {

	// Use this for initialization
    //public UnityEngine.UI.RawImage background; 
    public Transform m_tStairs,m_tInfo,m_tScore,m_tBackGround,m_tFallBall,m_tMusic;
    public GameObject m_pStair,m_pPlayer,m_pPlane,m_pBorder,m_pFireBallNotice,m_gLastStair,m_pFlyBird,m_gMusicButton;
    public RawImage m_btnSkill;
    private GameObject m_gPlayer;
    private int m_iFloor, m_iShowViewDirection;
    private UnityEngine.UI.Text m_tTime, m_sTime, m_sFloor, m_tFloor2, m_tLife, m_tReady, m_sFloorLocal, m_sTimeLocal, m_sResult, m_tStage;
    private float m_fFont, m_fTime, m_fFireBallTimer, m_fFlyBirdTimer;
    private bool m_bIsFirstRun,m_bIsFixBGWhenPreview;
    private PlayerScript m_spPlayer;
    private Slider m_slEnegy;
    private string m_CurMusic;
    public List<Transform> m_lstBG;

    void Start()
    {
        //CommonFunctionA.logger("角度：" + Mathf.Atan2(1f,1f)/Mathf.PI*180, 1);
        //初始化监听        
        CommonFunctionA.Initial().initialListener();//这句去掉可能引起按钮2次响应
        //CommonFunctionA.InitialAudio();//这个测试用，正式时不要
        InitialListener();
        //把一些游戏数据初始化
        InitialGameData();
        //初始化变量
        InitialMember();
        //开始生成Stair
        BeginGeneraling(GameData.gi.vBirthPoint);
        
        //GameObject gBGM=transform.parent.GetChild(2).gameObject;
        m_CurMusic = GameData.spi.gmi.sGameBackGroundMusic;
        //CommonFunctionA.logger("m_tMusic:" + m_tMusic.name, 1);
        //CommonFunctionA.PlayAudio(m_tMusic.gameObject, m_CurMusic);
        


    }
    
    void Update()
    {
        

        if (m_bIsFixBGWhenPreview)
        {
            FixBackGround(m_iShowViewDirection);
        }
        
        if (GameData.gi.bIsGameRunning)
        {
            //落石
            if (GameData.gi.SGR.fbpFallBall.bIsFalling)
            {
                //GameData.logger("有火球,时间:"+m_fFireBallTimer, 1);
                if (m_fFireBallTimer <= 0)
                {
                    if (m_fFireBallTimer != -1)
                    {
                        float floor = m_spPlayer.m_gCurStair.transform.position.y;
                        Vector3 v = new Vector3((int)UnityEngine.Random.Range(-GameData.gi.fHorzMaxBound, GameData.gi.fHorzMaxBound), floor + 15, GameData.pi.fZAxisFix);
                        //测试中间掉下来
                        //Vector3 v = new Vector3(0, floor + 15, GameData.pi.fZAxisFix);
                        GameObject gFireBall = Instantiate(m_pFireBallNotice, v, Quaternion.identity) as GameObject;
                        gFireBall.transform.parent = m_tFallBall;
                        int iType = 0;
                        if (GameData.GetRandomRate(GameData.gi.SGR.fbpFallBall.fFallBall2Rage))
                        {
                            iType = 2;
                            //CommonFunctionA.PlayAudio(gameObject, "fallball1");
                        }
                        else
                        {
                            iType = 1;
                            //CommonFunctionA.PlayAudio(gameObject, "fallball2");
                        }
                        gFireBall.GetComponent<FireBall>().InitialFireBall(iType, 5f);
                    }
                    m_fFireBallTimer = GameData.gi.SGR.fbpFallBall.fFallBallTime * (1 + UnityEngine.Random.Range(-1f, 1f) * GameData.gi.SGR.fbpFallBall.tFallBallTimeRandom);
                }
                else
                {
                    m_fFireBallTimer -= Time.deltaTime*GameData.gi.fGameSpeed;
                }

            }

            if (GameData.gi.SGR.fbpFallBall.bIsFlyBird)
            {
                if (m_fFlyBirdTimer <= 0)
                {
                    if (m_fFlyBirdTimer != -1)
                    {
                        float floor = m_spPlayer.m_gCurStair.transform.position.y;
                        Vector3 v = new Vector3(m_gPlayer.transform.position.x-8, floor + UnityEngine.Random.Range(-1f, 1f)*GameData.fbi.fFlyBirdRange, GameData.pi.fZAxisFix);
                        //测试中间掉下来
                        //Vector3 v = new Vector3(0, floor + 15, GameData.pi.fZAxisFix);
                        GameObject gFireBall = Instantiate(m_pFlyBird, v, Quaternion.identity) as GameObject;
                        gFireBall.transform.parent = m_tFallBall;
                        FireBall fb= gFireBall.GetComponent<FireBall>();
                        fb.m_tPlayer = m_gPlayer.transform;
                        fb.InitialFireBall(3, 10f);
                        
                    }
                    m_fFlyBirdTimer = GameData.gi.SGR.fbpFallBall.fFlyBirdTime * (1 + UnityEngine.Random.Range(-1f, 1f) * GameData.gi.SGR.fbpFallBall.tFlyBirdTimeRandom);
                }
                else
                {
                    m_fFlyBirdTimer -= Time.deltaTime * GameData.gi.fGameSpeed;
                }
            }
        }

        if (GameData.gi.bIsGameRunning)
        {
            m_fTime += Time.deltaTime * GameData.gi.fGameSpeed;
        }
        string s = SplitTime(m_fTime);
        m_tTime.text = s;
    }

    private void LoadGameData()
    {
        List<StairPropertyInfo> lst = GameData.lstSPI;
        int y=(int)m_gPlayer.GetComponent<PlayerScript>().m_gCurStair.transform.position.y;
        //CommonFunctionA.logger("m_gPlayer.GetComponent<PlayerScript>().m_gCurStair.transform.position.y--->" + m_gPlayer.GetComponent<PlayerScript>().m_gCurStair.transform.position.y, 1);
        for (int i = 0; i < lst.Count; i++)
        {
            //CommonFunctionA.logger("y:" + y + "GameData.gi.iStairNumPassed:" + GameData.gi.iStairNumPassed + " result: " + y / GameData.gi.iStairNumPassed, 1);
            //CommonFunctionA.logger("lst[i].iStage" + lst[i].iStage, 1);
            if (lst[i].iStage == y/GameData.gi.iStairNumPassed)
            {
                GameData.spi = lst[i];
                GameData.gi.SGR = lst[i].sgr;
                GameData.gii = lst[i].gii;
                break;
            }
        }
    }

    private void InitialListener()
    {
        //NotificationCenter.DefaultCenter().AddObserver(this, "GameMain_ShowFloor");
        NotificationCenter.DefaultCenter().AddObserver(this, "GameMain_GameOver");
        NotificationCenter.DefaultCenter().AddObserver(this, "GameMain_BeginGeneraling");
        NotificationCenter.DefaultCenter().AddObserver(this, "GameMain_MessageBox");
        NotificationCenter.DefaultCenter().AddObserver(this, "GameMain_FixBackGround");
        NotificationCenter.DefaultCenter().AddObserver(this, "GameMain_CallBackMoveObject");
        NotificationCenter.DefaultCenter().AddObserver(this, "GameMain_RefreshInterface");

    }

    private void InitialGameData()
    {
        GameData.GetInstance();
        GameData.pi.iLife = GameData.pi.iLifeSetting;
        GameData.gi.bIsGameMode = true;
        /*
        GameData.gi = new GameInfo();
        GameData.gi.SetValue(new Vector3(0, 0, -0.03f), 1, 1, 20, 7f, false, -0.02f,0,new StairGeneralRate(),3,true,-0.03f,20,5);
        GameData.ci = new CameraInfo();
        GameData.ci.SetValue(0.5f, -10f);
        GameData.qi = new QuestionInfo();
        GameData.GeneralQuestion(10);
        GameData.fbi = new FallBallInfo();
        GameData.fbi.SetValue(1f, 0.8f, 30f);
         */
    }

    private void InitialMember()
    {
        //将背景图片依次存入LIST
        for (int i = 0; i < m_tBackGround.childCount; i++)
        {
            Transform t = m_tBackGround.GetChild(i);
            m_lstBG.Add(t);
            t.GetChild(0).Translate(-GameData.gi.fHorzMaxBound - GameData.gi.fHorzValue, 0, 0);
            t.GetChild(1).Translate(GameData.gi.fHorzMaxBound + GameData.gi.fHorzValue, 0, 0);
        }
        //游戏启动
        GameData.gi.bIsGameRunning = true;
        //部份成员赋值。
        m_fFireBallTimer = -1;
        m_fFlyBirdTimer = -1;
        m_tScore.gameObject.SetActive(false);
        m_iFloor = 0;
        m_fTime = 0;
        m_bIsFirstRun = true;
        UnityEngine.UI.Text[] ts = m_tInfo.GetComponentsInChildren<UnityEngine.UI.Text>();
        for (int i = 0; i < ts.Length; i++)
        {
            if (ts[i].name == "tTime")
            {
                m_tTime = ts[i];
            }
            else if (ts[i].name == "tLife")
            {
                m_tLife = ts[i];
            }
            else if (ts[i].name == "t2")
            {
                m_tFloor2 = ts[i];
            }
            else if (ts[i].name == "tReady")
            {
                m_tReady = ts[i];
                m_tReady.gameObject.SetActive(false);
            }
            else if (ts[i].name == "tStage")
            {
                m_tStage = ts[i];
            }
        }
        ts = m_tScore.GetComponentsInChildren<UnityEngine.UI.Text>();
        for (int i = 0; i < ts.Length; i++)
        {
            //CommonFunctionA.logger("now:" + i + ",ts:" + ts[i], 1);
            if (ts[i].name == "tTime")
                m_sTime = ts[i];
            else if (ts[i].name == "t")
                m_sFloor = ts[i];
            else if (ts[i].name == "tTimeLocal")
                m_sTimeLocal = ts[i];
            else if (ts[i].name == "tLocal")
                m_sFloorLocal = ts[i];
            else if (ts[i].name == "tResult")
                m_sResult = ts[i];
            
        }

        m_slEnegy = m_tInfo.GetComponentInChildren<Slider>();

        m_tLife.text = GameData.pi.iLife.ToString();
        
    }

    public void GameMain_RefreshInterface(Notification n)
    {
        Hashtable adata = (Hashtable)n.data;
        RefreshInterface();
    }

    public void RefreshInterface()
    {
        if (GameData.pi.iEnegyNum == GameData.gi.iEnegyNumMax)
        {
            //能量满了，将按钮显示出来
            m_btnSkill.gameObject.SetActive(true);
            m_btnSkill.transform.GetChild(0).GetComponent<RawImage>().texture = CommonFunctionA.loadPicture("Skill_" + (GameData.pi.iChar + 1));
        }
        m_slEnegy.value = GameData.pi.iEnegyNum *1.0f / GameData.gi.iEnegyNumMax;
        m_tLife.text = GameData.pi.iLife.ToString();
    }

    public void FixBackGround(int iY)
    {
        //用来修复背景图移动
        Transform first = null, last = null;
        if (iY > 0)
        {
            first = m_lstBG[0];
            last = m_lstBG[m_lstBG.Count - 1];
        }
        else if (iY < 0)
        {
            first = m_lstBG[m_lstBG.Count - 1];
            last = m_lstBG[0];
        }

        if (iY > 0 || iY < 0)
        {
            if (last.GetComponent<Renderer>().isVisible)
            {
                Vector3 lastPosition = last.transform.position;
                Vector3 lastSize = (last.GetComponent<Renderer>().bounds.max - last.GetComponent<Renderer>().bounds.min);
                first.position = new Vector3(first.position.x, lastPosition.y + lastSize.y * iY, first.position.z);
                if (iY > 0)
                {
                    for (int i = 0; i < m_lstBG.Count - 1; i++)
                    {
                        m_lstBG[i] = m_lstBG[i + 1];
                    }
                    m_lstBG[m_lstBG.Count - 1] = first;
                }
                else if (iY < 0)
                {
                    for (int i = m_lstBG.Count - 1; i > 0; i--)
                    {
                        m_lstBG[i] = m_lstBG[i - 1];
                    }
                    m_lstBG[0] = first;
                }
            }
        }
    }

    public void GameMain_FixBackGround(Notification n)
    {
        Hashtable adata = (Hashtable)n.data;
        int iY = (int)adata["dirction"];
        FixBackGround(iY);
    }

    private void SetLevel(int iType)
    {
        //设置每关各种楼梯出现的概率
        /*
        switch (iType)
        {
            case 1:
                GameData.gi.SGR.SetValue(0.2f, 0.2f, 0.2f, 0.1f, 0.5f, new FallBallProp(true,2,0.5f,0.5f),1f);//这句测试用，把每种都显出来好测
                //GameData.gi.SGR.SetValue(0f, 0, 0, 0, 0, new FallBallProp(false, 0, 0, 0),1f);
                //GameData.gi.SGR.SetValue(0.2f, 0.2f, 0.1f, 0.1f, 0.3f, new FallBallProp(false, 0, 0, 0));

                //GameData.gi.SGR.SetValue(0.7f, 0.3f, 0, 0, 0,0, new FallBallProp(false, 0, 0, 0));
                break;                
                
            case 2:
                GameData.gi.SGR.SetValue(0.3f, 0.1f, 0, 0, 0, new FallBallProp(false, 0, 0, 0), 0.1f);
                break;

            case 3:
                GameData.gi.SGR.SetValue(0.3f, 0.2f, 0.1f, 0, 0, new FallBallProp(false, 0, 0, 0), 0.1f);
                break;

            case 4:
                GameData.gi.SGR.SetValue(0.2f, 0.2f, 0.1f, 0.1f, 0.3f, new FallBallProp(false, 0, 0, 0), 0.1f);
                break;

            case 5:
                GameData.gi.SGR.SetValue(0.2f, 0.2f, 0.2f, 0.1f, 0.4f, new FallBallProp(true, 5, 0.2f, 0), 0.1f);
                break;

            case 6:
                GameData.gi.SGR.SetValue(0.2f, 0.2f, 0.2f, 0.1f, 0.5f, new FallBallProp(true, 5, 0.2f, 0.5f), 0.1f);
                break;
        }
        if (iType > 6)
        {
            GameData.gi.SGR.SetValue(iType * 0.03f > 0.3f ? 0.3f : iType * 0.03f,
                iType * 0.03f > 0.3f ? 0.4f : iType * 0.03f, 
                iType * 0.02f > 0.3f ? 0.2f : iType * 0.03f,
                0.1f, 0.5f, new FallBallProp(true, 10 - iType * 0.5f < 2 ? 2 : 10 - iType * 0.5f, 0.2f, 0.5f), 0.1f);
        }

        if (GameData.gi.SGR.fbpFallBall.bIsFalling)
        {
            m_fFireBallTimer = GameData.gi.SGR.fbpFallBall.fFallBallTime;
        }
         */
    }

    public void GameMain_BeginGeneraling(Notification n)
    {
        Hashtable adata = (Hashtable)n.data;
        Vector3 v = (Vector3)adata["msg"];
        BeginGeneraling(v);
    }

    private void BeginGeneraling(Vector3 v)
    {
        //设定每关参数
        m_tStage.text = ((int)(v.y / (5 * 3 * GameData.gi.iStairNumPassed)) + 1) + "周目 " + 
            (((int)(v.y / (3 * GameData.gi.iStairNumPassed)))%5+1) +"-"+
            (((int)(v.y / (GameData.gi.iStairNumPassed))) % 3 + 1);
        int iType = (int)v.y / GameData.gi.iStairNumPassed + 1;
        //SetLevel(iType);
        //创建首个stair
        GameObject stair = Instantiate(m_pStair, v, Quaternion.identity) as GameObject;
        stair.name = "stair_" + m_iFloor;
        stair.GetComponent<StairProperty>().InitialStair(1, 0);
        
        //首次运行，生成玩家
        if (m_bIsFirstRun)
        {
            m_gPlayer = Instantiate(m_pPlayer, new Vector3(v.x, v.y + GameData.pi.fYAxisFix, GameData.pi.fZAxisFix), Quaternion.identity) as GameObject;
            GameData.pi.gPlayer = m_gPlayer;
            GameData.pi.pPlayer = m_pPlayer;
            m_spPlayer = m_gPlayer.GetComponent<PlayerScript>();
            if (m_spPlayer == null)
            {
                CommonFunctionA.logger("没有找到玩家的组件<PlayerScript>", 2);
                return;
            }
            m_spPlayer.m_tParent = m_tStairs;
            m_spPlayer.m_fFloor2 = m_tFloor2;
            //m_gPlayer.transform.position = stair.transform.position;
            //m_gPlayer.transform.Translate(0, GameData.pi.fYAxisFix, GameData.pi.fZAxisFix);
            m_bIsFirstRun = false;
            //如果玩家没有选（或测试），选用第一个角色
            string sCharPath = "char";
            int iCharNumber = GameData.pi.iChar + 1;
            sCharPath += iCharNumber;
            //CommonFunctionA.logger("char:"+sCharPath,1);
            m_gPlayer.GetComponent<SpriteRenderer>().sprite = CommonFunctionA.SetSpriteTexture(CommonFunctionA.loadPicture(sCharPath));
            StartCoroutine(BeginGeneraling2(0f, stair, v));
            //stair.gameObject.SetActive(false);
            //m_gPlayer.gameObject.SetActive(false);
        }
        else
        {
            //CommonFunctionA.Initial().ChangeCameraScene(-1, 0, 1);
            CommonFunctionA.ChangeCameraSizeTamplate(Camera.main.gameObject, 3.5f, 8, 2);
            CommonFunctionA.MoveObjectTamplate(Camera.main.gameObject, Camera.main.transform.position,
                new Vector3(0, Camera.main.transform.position.y, Camera.main.transform.position.z), 1, 0.5f);
            StartCoroutine(BeginGeneraling2(0.5f, stair, v));
        }
        m_spPlayer.m_gCurStair = stair;
        LoadGameData();
        //CommonFunctionA.logger("m_CurMusic:" + m_CurMusic + ", GameData.spi.sMusic:" + GameData.spi.sMusic, 1);
        if (m_CurMusic != GameData.spi.gmi.sGameBackGroundMusic)
        { 
            //说明要切换音乐了
            //CommonFunctionA.logger("要切换了:"+GameData.spi.sMusic,1);
            m_CurMusic = GameData.spi.gmi.sGameBackGroundMusic;
            CommonFunctionA.PlayAudio(m_gMusicButton, GameData.spi.gmi.sGameBackGroundMusic);
            m_gMusicButton.gameObject.GetComponent<AudioSource>().loop = true;
            //CommonFunctionA.logger("m_CurMusic " + m_CurMusic, 1);
            //切音乐时也跟着切背景
            for (int i = 0; i < m_lstBG.Count; i++)
            {
                m_lstBG[i].GetComponent<SpriteRenderer>().sprite = CommonFunctionA.SetSpriteTexture(CommonFunctionA.loadPicture(GameData.spi.gii.sGameBackGroundImage));
            }
        }
    }
    IEnumerator BeginGeneraling2(float time,GameObject stair,Vector3 v)
    {
        yield return new WaitForSeconds(time);
        //stair.gameObject.SetActive(true);
        //m_gPlayer.gameObject.SetActive(true);
        //成员记住首个stair的Y。
        GameData.gi.iTurnStartFloor = (int)stair.transform.position.y;
        
        //生成前，先前过去的全删除了
        for (int i = 0; i < m_tStairs.childCount; i++)
        {
            Destroy(m_tStairs.GetChild(i).gameObject);
        }
        //将首建stair加入父节点，同时终点生成平台。记住终点Y
        stair.transform.parent = m_tStairs;
        GeneralStairs(m_pStair, stair, 2 * GameData.gi.iStairNumPassed);//2倍的量，为的是中间有迂回；但也无妨，超过也会再次翻倍
        GameObject plane = Instantiate(m_pPlane, new Vector3(GameData.gi.vBirthPoint.x, v.y, 0), Quaternion.identity) as GameObject;
        plane.transform.parent = m_tStairs;
        plane.transform.Translate(0, 0, GameData.gi.fZAxisPlane);
        m_iShowViewDirection = 1;
        m_bIsFixBGWhenPreview = true;
        GameData.gi.bIsGameRunning = false;
        //这句有用的，移摄像机预览，测试时烦，先注释了
        
        CommonFunctionA.MoveObjectTamplate(Camera.main.gameObject,Camera.main.transform.position,
            new Vector3(0, m_gLastStair.transform.position.y + GameData.ci.fYAxisFix, GameData.ci.fZAxisFix),
            2,1f,"GameMain_CallBackMoveObject");
         
         
        //GameData.gi.bIsGameRunning = true; //这句临时加的，打开上面摄像机就删了
    }

    public void GameMain_CallBackMoveObject(Notification n)
    {
        //用于接收MOVE后的回调
        if (m_iShowViewDirection == 1)
        {
            m_iShowViewDirection = -1;
            
            CommonFunctionA.MoveObjectTamplate(Camera.main.gameObject, Camera.main.transform.position,
                new Vector3(0, GameData.gi.iTurnStartFloor + GameData.ci.fYAxisFix, GameData.ci.fZAxisFix),
                2, 1f, "GameMain_CallBackMoveObject");
        }
        else if (m_iShowViewDirection == -1)
        {
            m_bIsFixBGWhenPreview = false;
            //GameData.gi.bIsGameRunning = true;
            CommonFunctionA.PlayAudio(m_gPlayer, "ready");
            StartCoroutine(ReadyToGo(0.5f,1));
            
        }
    }

    private IEnumerator ReadyToGo(float time,int iType)
    {
        yield return new WaitForSeconds(time);
        if (iType == 1)
        {
            //移近视角
            CommonFunctionA.ChangeCameraSizeTamplate(Camera.main.gameObject, 8, 3.5f, 2);
            CommonFunctionA.MoveObjectTamplate(Camera.main.gameObject,Camera.main.transform.position,
                new Vector3(m_gPlayer.transform.position.x,Camera.main.transform.position.y,Camera.main.transform.position.z),1,0.5f);
            m_tReady.text = "Ready";
            m_tReady.gameObject.SetActive(true);
            CommonFunctionA.ShowFontTamplate(m_tReady.gameObject, 60f, 70f, 80);
            StartCoroutine(ReadyToGo(0.5f, 2));
        }
        else if (iType == 2)
        {
            m_tReady.text = "Go!";
            CommonFunctionA.ShowFontTamplate(m_tReady.gameObject, 60f, 70f, 80);
            StartCoroutine(ReadyToGo(0.5f, 3));
        }
        else if (iType == 3)
        {
            m_tReady.gameObject.SetActive(false);
            GameData.gi.bIsGameRunning = true;
        }
    }


    public void GameMain_MessageBox(Notification n)
    {
        //弹出问题框
        Hashtable adata = (Hashtable)n.data;
        MsgBox MBquestion = (MsgBox)adata["msg"];
        CommonFunctionA.Initial().MessageBox(m_pBorder, MBquestion);
        GameData.gi.bIsGameRunning = false;
    }

    public void GameMain_GameOver()
    {
        //游戏结束，1秒后显示分数信息
        CommonFunctionA.PlayAudio(gameObject, "fail");                
        m_sTime.text = m_tTime.text;
        m_sFloor.text = m_tFloor2.text;
        m_gPlayer.transform.GetChild(1).gameObject.SetActive(true);
        GameData.gi.bIsGameRunning = false;        
        StartCoroutine(GameOver(1));
        //CommonFunctionA.Initial().ChangeCameraScene(0, -1, 1);
    }


    IEnumerator GameOver(float time)
    {
        yield return new WaitForSeconds(time);
        //if (!GameData.gi.bIsGameMode) NotificationCenter.DefaultCenter().PostNotification(this, "HelpMain_Dead", null);
        GameData.pi.iLife--;
        CommonFunctionA.m_bIsRestart = true;
        if (GameData.pi.iLife > 0)
        {
            //将玩家一些属性回归
            m_slEnegy.value = 0;
            GameData.pi.iEnegyNum = 0;
            //将玩家的重力（如有）移除，并将其移至生成的楼梯上，变白
            Destroy(m_gPlayer.GetComponent<Rigidbody2D>());
            m_spPlayer.m_bIsJump = false;
            m_spPlayer.m_bIsFinishJump = true;
            m_btnSkill.gameObject.SetActive(false);
            m_gPlayer.GetComponent<SpriteRenderer>().color = Color.white;
            Transform tPlayer = GameData.pi.gPlayer.transform;
            for (int i = 0; i < tPlayer.childCount; i++)
            {
                if (tPlayer.GetChild(i).name == "Border")
                {
                    tPlayer.GetChild(i).gameObject.SetActive(false);
                }
            }
            GameData.pi.iPlayerStatus = 0;
            


            //清空落石，以防连死
            for (int i = 0; i < m_tFallBall.childCount; i++)
            {
                Destroy(m_tFallBall.GetChild(i).gameObject);
            }
            float fStairNow = m_spPlayer.m_gCurStair.transform.position.y;
            int iStairStar = ((int)fStairNow / GameData.gi.iStairNumPassed) * GameData.gi.iStairNumPassed;
            m_tLife.text = GameData.pi.iLife.ToString();            
            m_gPlayer.transform.position = new Vector3(0, iStairStar+GameData.pi.fYAxisFix, GameData.pi.fZAxisFix);
            Camera.main.transform.position = new Vector3(0, iStairStar + GameData.ci.fYAxisFix, GameData.ci.fYAxisFix);
            //背景都下移
            for (int i = 0; i < m_tBackGround.childCount; i++)
            {
                m_tBackGround.GetChild(0).localPosition = new Vector3(0, iStairStar, 0);
                m_tBackGround.GetChild(1).localPosition = new Vector3(0, iStairStar + 10, 0);
                m_tBackGround.GetChild(2).localPosition = new Vector3(0, iStairStar + 20, 0);
            }
            m_gPlayer.transform.GetChild(0).gameObject.SetActive(false);
            BeginGeneraling(new Vector3(0, iStairStar, GameData.gi.vBirthPoint.z));
        }
        else
        {
            int iFloorLocal=PlayerPrefs.GetInt("iFloorLocal");
            if (iFloorLocal == 0)
            {
                m_sFloorLocal.text = "--";
                m_sTimeLocal.text = "--'--.--";
            }
            else
            {
                m_sFloorLocal.text = iFloorLocal.ToString() ;
                m_sTimeLocal.text = PlayerPrefs.GetString("sTimeLocal");
                
            }

            if (int.Parse(m_tFloor2.text) > iFloorLocal)
            {
                m_sResult.text = "恭喜您！新的纪录产生了！";
                //CommonFunctionA.logger("写入纪录：时间为:" + m_tTime.text + ",层数为：" + int.Parse(m_tFloor2.text), 1);
                PlayerPrefs.SetString("sTimeLocal", m_tTime.text);
                PlayerPrefs.SetInt("iFloorLocal", int.Parse(m_tFloor2.text));
            }
            else
            {
                m_sResult.text = "很遗憾！上次的状态更好！";
            }
            m_sFloor.text = m_tFloor2.text;
            m_sTime.text = m_tTime.text;
            m_tScore.gameObject.SetActive(true);
        }
    }
    /*
    public void GameMain_ShowFloor()
    {
        //刷新玩家边上的数字层数
        float floor = m_spPlayer.m_gCurStair.transform.position.y;
        m_tFloor2.text = floor.ToString();
        Hashtable adata = new Hashtable();
        adata["msg"] = floor;
        NotificationCenter.DefaultCenter().PostNotification(this, "PlayerScript_ShowFloor", adata);
    }
    */
    private string SplitTime(float fTime)
    {
        TimeSpan ts = new TimeSpan(0, 0, (int)fTime);
        float f = ((int)(fTime * 100)) % 100;
        string m, s, ms;
        m = ts.Minutes.ToString();
        s = ts.Seconds.ToString();
        ms = f.ToString();
        if (m.Length == 1) m = "0" + m;
        if (s.Length == 1) s = "0" + s;
        if (ms.Length == 1) ms = "0" + m;
        if (ms == "000") ms = "00";
        return m+"'"+s+"."+ms;
    }

    private GameObject InitialStair(GameObject pStair, Vector3 v, Transform tParent)
    {
        //创建单个stair
        GameObject stair = Instantiate(pStair, v, Quaternion.identity) as GameObject;
        stair.name = "stair_" + ++m_iFloor;
        stair.transform.parent = tParent;
        stair.GetComponent<StairProperty>().m_bIsLive = true;
        return stair;
    }

    private void GeneralStairs(GameObject pStair, GameObject lastStair, int number)
    {
        //生成多个stair
        for (int i = 0; i < number; i++)
        {
            Vector3 v= GeneralPosition(lastStair);
            GameObject stair =InitialStair(pStair, v, m_tStairs);
            lastStair = stair;
            //CommonFunctionA.logger("生成了一个平台"+stair.name, 1);
            //生成终点平台
            if (v.y % GameData.gi.iStairNumPassed == 0 && v.y != GameData.gi.iTurnStartFloor && v.y != 0)
            {
                GameObject plane = Instantiate(m_pPlane, new Vector3(0, stair.transform.position.y,GameData.gi.fZAxisPlane), Quaternion.identity);
                plane.transform.parent = m_tStairs;
                stair.GetComponent<StairProperty>().InitialStair(1, 0);
                for (int j = 0; j < stair.transform.childCount; j++)
                {
                    Transform t = stair.transform.GetChild(j);
                    if (t.name == "Effect")
                    {
                        t.GetComponent<SpriteRenderer>().sprite = CommonFunctionA.SetSpriteTexture(CommonFunctionA.loadPicture("ending"));
                        t.gameObject.SetActive(true);
                    }
                }
                break;
            }
            //如果到了上限，还是没有完成，继续建
            if (i == (number - 1) && stair.transform.position.y % GameData.gi.iStairNumPassed != 0)
            {
                number *= 2;
            }

            StairProperty sp = stair.GetComponent<StairProperty>();
            
            if (sp != null)
            {
                if (GameData.GetRandomRate(GameData.gi.SGR.fFallingStair1Rate))
                {
                    //计时梯
                    sp.InitialStair(2, 3);
                    //CommonFunctionA.logger("这个是计时梯", 1);
                    continue;
                }

                if (GameData.GetRandomRate(GameData.gi.SGR.fFallingStair2Rate))
                {
                    //计时梯2
                    sp.InitialStair(2, 1);
                    //CommonFunctionA.logger("这个是计时梯2", 1);
                    continue;
                }

                if (GameData.GetRandomRate(GameData.gi.SGR.fFireStairRate))
                {
                    //火梯
                    sp.InitialStair(3, 3.5f + UnityEngine.Random.Range(-2.0f, 1.0f));
                    //CommonFunctionA.logger("这个是火梯", 1);
                    continue;
                }

                if (GameData.GetRandomRate(GameData.gi.SGR.fQuestionStairRage))
                {
                    //分支梯，如果到离终点只差1步了，就不建分支梯了。
                    if ((stair.transform.position.y + 1) % GameData.gi.iStairNumPassed != 0 && (stair.transform.position.y) % GameData.gi.iStairNumPassed != 0)
                    {
                        //如果左上，上，右上都为空，则可以选择3个答案或2个答案
                        bool b1, b2, b3;
                        if (stair.transform.position.x - GameData.gi.fHorzValue < -GameData.gi.fHorzMaxBound)
                        {
                            b1 = false;
                        }
                        else
                        {
                            b1 = isStairExist(new Vector3(stair.transform.position.x - GameData.gi.fHorzValue,
                                stair.transform.position.y + GameData.gi.fVertValue,
                                stair.transform.position.z));
                        }
                        b2 = isStairExist(new Vector3(stair.transform.position.x, 
                            stair.transform.position.y + GameData.gi.fVertValue,
                            stair.transform.position.z));

                        if (stair.transform.position.x + GameData.gi.fHorzValue > GameData.gi.fHorzMaxBound)
                        {
                            b3 = false;
                        }
                        else
                        {
                            b3 = isStairExist(new Vector3(stair.transform.position.x + GameData.gi.fHorzValue, 
                                stair.transform.position.y + GameData.gi.fVertValue, 
                                stair.transform.position.z));
                        }
                        
                        if (!b1 && !b2 && !b3)
                        {
                            int r = UnityEngine.Random.Range(0, GameData.qi.LstQuestions.Count);
                            sp.InitialStair(4, 0, new MsgBox("［数学题］", GameData.qi.LstQuestions[r].sQuestion, "关闭", GameData.gi.fMsgBoxAutoCloseSec));
                            if (GameData.GetRandomRate(GameData.gi.SGR.fQuestionStair3Rage))
                            {
                                stair = GeneralQuestionStairs(pStair, 2, stair, r);
                            }
                            else
                            {
                                stair = GeneralQuestionStairs(pStair, 3, stair, r);
                            }
                            lastStair = stair;
                            continue;
                        }
                        lastStair = stair;
                    }
                    //CommonFunctionA.logger("这个是分支梯", 1);
                    
                }

                //如果程序运行到这里，说明前面都没建特殊stair，则这里直接建普通stair
                //CommonFunctionA.logger("这个是普通梯", 1);

                sp.InitialStair(1, 0);
            }
        }
        m_gLastStair = lastStair;
    }

    private bool isStairExist(Vector3 v)
    {
        //返回某点是否存在stair
        Collider[] colliders = Physics.OverlapSphere(v, 0.5f);
        if(colliders.Length==0)
        {
            return false;
        }
        else return true;
    }

    private GameObject GeneralQuestionStairs(GameObject pStair,int Number, GameObject lastStair,int iQuestionId)
    {
        //如果数字是2，则有2个答案，在左上，上，右上中随机生成2个即可，是3个的话就是三条线
        Vector3 v0 = new Vector3(lastStair.transform.position.x - GameData.gi.fHorzValue,
            lastStair.transform.position.y + GameData.gi.fVertValue,
            lastStair.transform.position.z);
        Vector3 v1 = new Vector3(lastStair.transform.position.x,
            lastStair.transform.position.y + GameData.gi.fVertValue,
            lastStair.transform.position.z);
        Vector3 v2 = new Vector3(lastStair.transform.position.x + GameData.gi.fHorzValue,
            lastStair.transform.position.y + GameData.gi.fVertValue,
            lastStair.transform.position.z);
        Vector3 v3 = new Vector3(lastStair.transform.position.x,
            lastStair.transform.position.y + 2*GameData.gi.fVertValue,
            lastStair.transform.position.z);
        MsgBox Mb=new MsgBox();//无用的，填充默认参数
        GameObject g1 = null, g2 = null, g3 = null;
        if (Number == 2)
        {
            if (GameData.GetRandomRate(0.33f))
            {
                //左上一个楼梯
                {
                    g1 = InitialStair(pStair, v0, m_tStairs);
                }
                if (GameData.GetRandomRate(0.5f))
                {
                    //上一个楼梯
                    g2 = InitialStair(pStair, v1, m_tStairs);
                }
                else
                {
                    //右上一个楼梯
                    g2 = InitialStair(pStair, v2, m_tStairs);
                }
            }
            else
            {
                //上，右上两个楼梯
                g1 = InitialStair(pStair, v1, m_tStairs);
                g2 = InitialStair(pStair, v2, m_tStairs);
            }
            if (GameData.GetRandomRate(0.5f))
            {
                g1.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 1);
                g2.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 2);
            }
            else
            {
                g2.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 1);
                g1.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 2);
            }
        }
        else if (Number == 3)
        {
            g1 = InitialStair(pStair, v0, m_tStairs);
            g1.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 1);
            g2 = InitialStair(pStair, v1, m_tStairs);
            g2.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 2);
            g3 = InitialStair(pStair, v2, m_tStairs);
            g3.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 3);
            if (GameData.GetRandomRate(0.333f))
            {
                g1.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 1);
                g2.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 2);
                g3.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 3);
            }
            else               
            {
                if (GameData.GetRandomRate(0.5f))
                {
                    g2.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 1);
                    g1.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 2);
                    g3.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 3);
                }
                else
                {
                    g3.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 1);
                    g2.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 2);
                    g1.GetComponent<StairProperty>().InitialStair(5, 0, Mb, iQuestionId, 3);
                }
            }
        }
        if(g1!=null)
            g1.transform.parent = lastStair.transform;
        if (g2 != null)
            g2.transform.parent = lastStair.transform;
        if (g3 != null)
            g3.transform.parent = lastStair.transform;

        //在上上方生成一个普通
        GameObject stair =InitialStair(pStair, v3, m_tStairs);
        stair.GetComponent<StairProperty>().InitialStair(1, 0);
        return stair;
    }

    private Vector3 GeneralPosition(GameObject lastStair)
    {
        //为保证stair正常向上，写死方向的比例了：向上7成，左右2成，向下1成
        bool a00,a01,a02,a10,a12,a20,a21,a22;
        a00 = a01 = a02 = a10 = a12 = a20 = a21 = a22 = true;
        Vector3 v=lastStair.transform.position;
        for (int i = 0; i < 8; i++)
        {
            if (GameData.GetRandomRate(0.7f))
            {
                //说明向上，左右各4成，上2成
                if (GameData.GetRandomRate(0.2f) && a01)
                {
                    //向上 a01
                    v=new Vector3(lastStair.transform.position.x, lastStair.transform.position.y + GameData.gi.fVertValue, GameData.gi.fZAxisStair);
                    bool b=isStairExist(v);
                    if (b) { a01 = false; continue; }
                    else break;
                }
                else if (GameData.GetRandomRate(0.5f) && a00)
                {
                    //向左上
                    if (lastStair.transform.position.x == GameData.gi.fHorzMaxBound * -1)
                    {
                        a00 = false; continue; 
                    }
                    v = new Vector3(lastStair.transform.position.x - GameData.gi.fHorzValue, lastStair.transform.position.y + GameData.gi.fVertValue, GameData.gi.fZAxisStair);
                    bool b = isStairExist(v);
                    if (b) { a00 = false; continue; }
                    else break;
                }
                else if(a02)
                {
                    //向右上
                    if (lastStair.transform.position.x == GameData.gi.fHorzMaxBound * 1)
                    {
                        a02 = false; continue; 
                    }
                    v = new Vector3(lastStair.transform.position.x + GameData.gi.fHorzValue, lastStair.transform.position.y + GameData.gi.fVertValue, GameData.gi.fZAxisStair);
                    bool b = isStairExist(v);
                    if (b) { a02 = false; continue; }
                    else break;
                }
            }
            else if (GameData.GetRandomRate(0.66f))
            {
                //说明左右，各5成
                if (GameData.GetRandomRate(0.5f)&& a10)
                {
                    //向左
                    if (lastStair.transform.position.x == GameData.gi.fHorzMaxBound * -1)
                    {
                        a10 = false; continue;
                    }
                    v = new Vector3(lastStair.transform.position.x - GameData.gi.fHorzValue, lastStair.transform.position.y, GameData.gi.fZAxisStair);
                    bool b = isStairExist(v);
                    if (b) { a10 = false; continue; }
                    else break;
                }
                else if(a12)
                {
                    //向右
                    if (lastStair.transform.position.x == GameData.gi.fHorzMaxBound * 1)
                    {
                        a12 = false; continue;
                    }
                    v = new Vector3(lastStair.transform.position.x + GameData.gi.fHorzValue, lastStair.transform.position.y, GameData.gi.fZAxisStair);
                    bool b = isStairExist(v);
                    if (b) { a12 = false; continue; }
                    else break;
                }
            }
            else
            {
                //向下，左右各4成，上2成
                if (lastStair.transform.position.y % GameData.gi.iStairNumPassed == 0 || lastStair.transform.position.y==-1)
                {
                    //起点不向下
                    a21 = a22 = a20 = false; continue;
                }
                if (GameData.GetRandomRate(0.2f)&&a21)
                {
                    //向下
                    v = new Vector3(lastStair.transform.position.x, lastStair.transform.position.y - GameData.gi.fVertValue, GameData.gi.fZAxisStair);
                    bool b = isStairExist(v);
                    if (b) { a21 = false; continue; }
                    else break;
                }
                else if (GameData.GetRandomRate(0.5f)&&a20)
                {
                    //向左下
                    if (lastStair.transform.position.x == GameData.gi.fHorzMaxBound * -1)
                    {
                        a20 = false; continue;
                    }
                    v = new Vector3(lastStair.transform.position.x - GameData.gi.fHorzValue, lastStair.transform.position.y - GameData.gi.fVertValue, GameData.gi.fZAxisStair);
                    bool b = isStairExist(v);
                    if (b) { a20 = false; continue; }
                    else break;
                }
                else if(a22)
                {
                    //向右下
                    if (lastStair.transform.position.x == GameData.gi.fHorzMaxBound * 1)
                    {
                        a22 = false; continue;
                    }
                    v = new Vector3(lastStair.transform.position.x + GameData.gi.fHorzValue, lastStair.transform.position.y - GameData.gi.fVertValue, GameData.gi.fZAxisStair);
                    bool b = isStairExist(v);
                    if (b) { a22 = false; continue; }
                    else break;
                }
            }
        }
        return v;
    }
    
}
